<template>
  <div class="order-detail">
    <div class="order-detail-info">
      <div class="order-detail-info-number">编号 {{ orderDetail.code }}</div>
      <div class="order-detail-info-title">{{ orderDetail?.project?.name || "--" }}</div>
      <div class="order-detail-info-status">
        <AuthTable :permissions="resourceButton" key-string="orderStatus">
          <!-- <template #edit>
            <TriggerContext
              class="trigger-context-status"
              :component="Status"
              :props="{
                id: orderDetail.status,
                list: dealOrderStatus(getDict('orderStatus')),
                handleDateChange: (date: any) => {
                  editHandler({
                    projectId: projectId,
                    orderId: orderId,
                    tableName: getTableName('status'),
                    fieldName: 'status',
                    newValue: date
                  });
                }
              }"
            >
              <div class="order-detail-info-status-item">
                <div class="icon"></div>
                <div class="status">
                  <span>{{ orderDetail.status ? getDictItem("orderStatus", orderDetail.status) : "--" }}</span>
                  <span>当前状态</span>
                </div>
              </div>
            </TriggerContext>
          </template> -->
          <template #edit>
            <div class="order-detail-info-status-item">
              <!-- <div class="icon"></div> -->
              <div class="status">
                <span>{{ orderDetail.status ? getDictItem("orderStatus", orderDetail.status) : "--" }}</span>
                <span>当前状态</span>
              </div>
            </div>
          </template>
          <template #get>
            <div class="order-detail-info-status-item">
              <!-- <div class="icon"></div> -->
              <div class="status">
                <span>{{ orderDetail.status ? getDictItem("orderStatus", orderDetail.status) : "--" }}</span>
                <span>当前状态</span>
              </div>
            </div>
          </template>
        </AuthTable>
        <div class="order-detail-info-status-item default">
          <!-- <div class="icon icon-date">
            <el-icon><Calendar /></el-icon>
          </div> -->
          <div class="status">
            <span>{{ orderDetail.orderTime ? dayjs(orderDetail.orderTime).format("MM月DD日") : "--" }}</span>
            <span>下单时间</span>
          </div>
        </div>
        <div class="order-detail-info-status-item default">
          <!-- <div class="icon icon-date">
            <el-icon><Calendar /></el-icon>
          </div> -->
          <div class="status">
            <span>{{ orderDetail.planDeliveryTime ? dayjs(orderDetail.planDeliveryTime).format("MM月DD日") : "--" }}</span>
            <span>计划发货时间</span>
          </div>
        </div>
        <div class="order-detail-info-status-item default">
          <!-- <div class="icon icon-date">
            <el-icon><Calendar /></el-icon>
          </div> -->
          <div class="status">
            <span>{{
              orderDetail?.project?.planEndTime ? dayjs(orderDetail.project.planEndTime).format("MM月DD日") : "--"
            }}</span>
            <span>计划验收日期</span>
          </div>
        </div>
      </div>
      <div class="order-detail-info-item">
        <Tabs :list="tabs" @change="tabsChangeHandler" :active="tabsActive">
          <template #member>
            <div>
              成员<span class="count" :class="{ count_active: isTabsActive('member') }">{{ countList["member"] }}</span>
            </div>
          </template>
          <template #track>
            <div>
              进度跟踪<span class="count" :class="{ count_active: isTabsActive('track') }">{{ countList["track"] }}</span>
            </div>
          </template>
          <template #document>
            <div>
              文档<span class="count" :class="{ count_active: isTabsActive('document') }">{{ countList["document"] }}</span>
            </div>
          </template>
        </Tabs>
      </div>
      <div class="order-detail-info-content">
        <component
          :is="tabsComponent"
          v-if="tabsComponent"
          v-bind="{ projectId, resourceButton, orderId, orderDetail }"
          @count="countChangeHandler"
        ></component>
      </div>
    </div>
    <div class="order-detail-log">
      <div class="order-detail-log-title">订单日志</div>
      <div class="order-detail-log-list">
        <div class="order-detail-log-list-item" v-for="item in logList" :key="item">
          <!-- 第一版 -->
          <!-- <div class="order-detail-log-list-item-avatar"><img :src="urlResource + item.avatarUrl" alt="" /></div>
          <div class="order-detail-log-list-item-info">
            <span class="mb6">{{ item.userName }}</span>
            <span>
              {{ dayjs(item.operationTime).format("YYYY年MM月DD日") }}
              <s style="color: #999999" class="mr4">{{ item.operationType }}</s>
              <s style="color: var(--el-color-primary)">{{ item.changedFields.join(",") || "--" }}</s>
            </span>
            <span v-for="itm in item.changedFields" :key="`${item.id}_${itm}`">
              <template v-if="item.changedFields">
                [{{ item.beforeValue[itm] || "--" }}]
                <s class="ml4 mr4" style="position: relative; top: 5px; font-size: 18px; color: var(--el-color-primary)">
                  <el-icon><Right /></el-icon>
                </s>
                [{{ item.afterValue[itm] || "--" }}]
              </template>
            </span>
          </div> -->

          <!-- 第二版 -->
          <div class="order-detail-log-laster">
            <span class="order-detail-log-laster-line"></span>
            <div class="order-detail-log-laster-cot">
              <div class="order-detail-log-laster-cot-item">
                <span>人员：</span>
                <span>{{ item.userName }}</span>
              </div>
              <div class="order-detail-log-laster-cot-item">
                <span>{{ item.operationType || "--" }}：</span>
                <span style="color: var(--el-color-primary)">{{ item.changedFields[0] || "--" }}</span>
              </div>
              <div class="order-detail-log-laster-cot-item">
                <span>修改前：</span>
                <span>{{ item.beforeValue[item.changedFields[0]] || "--" }}</span>
              </div>
              <div class="order-detail-log-laster-cot-item">
                <span>修改后：</span>
                <span>{{ item.afterValue[item.changedFields[0]] || "--" }}</span>
              </div>
              <div class="order-detail-log-laster-cot-item">
                <span>时间：</span>
                <span>{{ item.operationTime }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="close-icon" @click="closeHandler">
      <el-icon><Close /></el-icon>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { ref, computed, onMounted, provide } from "vue"; // inject
import { Close } from "@element-plus/icons-vue";
import type { Component } from "vue";
import Tabs from "@/components/Tabs/index.vue";
import { useAuthButtons } from "@/hooks/useAuthButtons";
import { Info, Document, ContractDetail, Member, Mileage, Track, Customize, Design } from "./components/index";
// import { Status } from "./components/index";
import { useDict } from "@/hooks/useDict";
import { getOrderDetail, getOrderLogQuery } from "@/api/modules/order"; // getOrderUpdate
// import TriggerContext from "@/components/TriggerContext/index.vue";
import AuthTable from "@/components/AuthTable/index.vue";
import dayjs from "dayjs";

const { BUTTONS } = useAuthButtons("designDrawing");

const { getDictItem } = useDict(["orderStatus"]); // getDict
// const mainTableRef = inject<any>("mainTableRef");
// const urlResource = inject<any>("urlResource");

const { orderId, projectId, resourceButton, tabIndex } = defineProps({
  orderId: {
    type: String,
    default: ""
  },
  projectId: {
    type: String,
    default: ""
  },
  resourceButton: {
    type: Object,
    default: () => {}
  },
  tableColumns: {
    type: Array,
    default: () => []
  },
  tabIndex: {
    type: Number,
    default: 0
  }
}); // tableColumns
const detailVisible = defineModel("detailVisible", {
  type: Boolean,
  default: false
});

const orderDetail = ref<any>({});

const countList = ref<any>({
  member: 0,
  track: 0,
  document: 0
});

const logList = ref<any>([]);

const closeHandler = () => {
  detailVisible.value = false;
};

/**
 * tab
 */

const tabs = ref([
  {
    name: "订单信息",
    key: "info"
  },
  {
    name: "合同标的",
    key: "contract"
  },
  {
    name: "非标定制项",
    key: "customize"
  },
  {
    name: "成员",
    key: "member"
  },
  {
    name: "里程碑",
    key: "mileage"
  },
  {
    name: "进度跟踪",
    key: "track"
  },
  {
    name: "文档",
    key: "document"
  }
]);

const tabsComponentMapping = ref<Record<string, Component>>({
  info: Info,
  contract: ContractDetail,
  member: Member,
  mileage: Mileage,
  track: Track,
  document: Document,
  customize: Customize
});

if (BUTTONS.value["get"]) {
  tabs.value.splice(6, 0, {
    name: "设计图",
    key: "design"
  });
  tabsComponentMapping.value["design"] = Design;
}

const tabsActive = ref(tabIndex);
const isTabsActive = (key: string) => {
  return tabs.value[tabsActive.value]["key"] === key;
};
const tabsComponent = computed(() => {
  const key: any = tabs.value[tabsActive.value]["key"];
  return tabsComponentMapping.value[key];
});
const tabsChangeHandler = (options: any) => {
  const { index } = options;
  tabsActive.value = index;
};

const getOrderDetailHandler = async () => {
  const { data } = await getOrderDetail({ id: orderId });
  orderDetail.value = data;
  countList.value["member"] = orderDetail.value?.project?.userModels?.length || 0;
  countList.value["track"] = orderDetail.value?.orderFollowList?.length || 0;
  countList.value["document"] = orderDetail.value?.project?.fileModels?.length || 0;
};
provide("refresh", getOrderDetailHandler);
// 获取表名
// const getTableName = (key: string) => {
//   return tableColumns.find((item: any) => item.key === key)?.tableName;
// };
// 编辑订单
// const editHandler = async (params: any) => {
//   await getOrderUpdate(params);
//   getOrderDetailHandler();
//   mainTableRef.value.refresh();
// };

const countChangeHandler = (options: any) => {
  const { key, count } = options;
  countList.value[key] = count;
};

// 处理订单列表状态
// const colorOrderStatus = ["#C8CEE0", "#3F4DE6", "#F6B853", "#3FE64A", "#7C7C7C"];
// const colorOrderStatusMap: any = {};
// const dealOrderStatus = (list: any) => {
//   return (
//     (list &&
//       list.map((item: any, index: number) => {
//         item.color = colorOrderStatus[index];
//         colorOrderStatusMap[item.id] = item.color;
//         return item;
//       })) ||
//     []
//   );
// };

const getOrderLogQueryFn = async () => {
  const { data } = await getOrderLogQuery({ orderId });
  logList.value = data;
  console.log(logList.value);
};

onMounted(() => {
  getOrderDetailHandler();
  getOrderLogQueryFn();
});
</script>
<style lang="scss" scoped>
.order-detail {
  display: flex;
  justify-content: space-between;
  height: 100%;

  position: relative;
  .close-icon {
    position: absolute;
    right: 15px;
    top: 15px;
    font-size: 16px;
    cursor: pointer;
  }
  &-info {
    display: flex;
    flex: 1;
    flex-flow: column nowrap;
    padding-top: 12px;
    padding-left: 20px;
    &-number {
      flex: 0 0 27px;
      box-sizing: border-box;
      width: fit-content;
      padding: 4px 10px;
      font-size: 14px;
      font-weight: 400;
      color: #333333;
      background: #f9f9f9;
      border-radius: 2px;
    }
    &-title {
      flex: 0 0 31px;
      margin: 20px 0 30px;
      font-size: 24px;
      color: #333333;
    }
    &-status {
      display: flex;
      flex: 0 0 40px;
      gap: calc((70% - 130px * 4) / 4);
      &-item {
        display: flex;
        flex: 0 0 130px;
        margin-left: 10px;
        cursor: default;
        .icon {
          flex: 0 0 36px;
          width: 36px;
          height: 36px;
          margin-right: 10px;
          // background: #000000;
          border-radius: 50%;
          img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            border-radius: 50%;
          }
        }
        .icon-date {
          background: transparent;
          border: 1px dashed #cccccc;
          display: flex;
          justify-content: center;
          align-items: center;
          font-size: 14px;
          cursor: default;
        }
        .status {
          display: flex;
          flex: 1;
          flex-flow: column nowrap;
          font-size: 14px;
          line-height: 20px;
          color: #333333;
          span:last-child {
            font-size: 12px;
            color: #999999;
          }
        }
      }
      .default {
        cursor: default;
      }
    }
    &-item {
      flex: 0 0 36px;
      margin-top: 32px;
      &-content {
        flex: 1;
      }
      .count {
        margin-left: 2px;
        color: rgb(153 153 153 / 100%);
        &_active {
          color: $primary-color;
        }
      }
    }
    &-content {
      flex: 1;
      padding: 30px 20px 0 0px;
      overflow: hidden;
      box-sizing: border-box;
    }
  }
  &-log {
    display: flex;
    flex: 0 0 390px;
    flex-flow: column nowrap;
    border-left: 1px solid rgb(244 244 244 / 100%);
    &-title {
      box-sizing: border-box;
      flex: 0 0 60px;
      padding: 20px 30px;
      font-size: 14px;
      font-weight: 600;
      color: rgb(153 153 153 / 100%);
      color: #333333;
      border-bottom: 1px solid rgb(244 244 244 / 100%);
    }
    &-list {
      flex: 1;
      padding: 24px 24px 0 24px;
      overflow: auto;
      background-color: #ffffff;
      &-item {
        display: flex;
        padding-bottom: 20px;
        border-left: 1px solid #f1f1f1;
        &-avatar {
          width: 36px;
          height: 36px;
          margin-right: 10px;
          border-radius: 50%;
          img {
            width: 100%;
            height: 100%;
            border-radius: 50%;
            object-fit: contain;
          }
        }
        &-info {
          display: flex;
          flex-flow: column nowrap;
          font-size: 14px;
          line-height: 20px;
          color: #333333;
          width: 300px;
          // span:last-child {
          //   font-size: 12px;
          //   color: #333333;
          // }
        }
      }
    }
    // 第二版
    &-laster {
      display: flex;
      flex-flow: column nowrap;
      width: 100%;
      &-line {
        height: 100%;
        width: 1px;
        background: #f1f1f1;
        position: relative;
        &:after {
          display: block;
          content: "";
          width: 7px;
          height: 7px;
          background: var(--el-color-primary);
          border-radius: 50%;
          position: absolute;
          top: 0;
          left: -4px;
          outline: 4px solid #ffffff;
        }
      }
      &-cot {
        width: 100%;
        &-item {
          width: 100%;
          display: flex;
          margin-bottom: 10px;
          span:first-child {
            flex: 0 0 80px;
            text-align: right;
            color: #999;
          }
          span:last-child {
            flex: 1;
            color: #333;
          }
        }
      }
    }
  }
  :deep(.wik-document) {
    padding: 0;
  }
}
</style>
